import urllib
import os
import logging

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class Student(db.Model):
  name = db.StringProperty(required=True)
  location = db.StringProperty(required=True)

class MapHandler(webapp.RequestHandler):
  def get(self):
    students = Student.all()
    
    locations = [student.location for student in students]    
    location_value = '|'.join(locations)

    names = [student.name for student in students]
    names_formatted = []
    i = 0
    for name in names :
      l = 'f%s,000000,0,%d,10' % (name, i)
      names_formatted.append(l)
      i += 1  
    name_value = '|'.join(names_formatted)

    template_values = {'locations': location_value,
                       'labels': name_value,
                       'students': students}
    path = os.path.join(os.path.dirname(__file__), 'map.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):
    name = self.request.get('name')
    location = self.request.get('location')
    student_to_delete = self.request.get('student')

    if name and location:
      student = Student(name=name, location=location)
      student.put()
    
    if student_to_delete:
      student = Student.get(student_to_delete)
      if student:
        student.delete()
  
    self.get()

def main():
  application = webapp.WSGIApplication([('/', MapHandler)],
                                       debug=True)
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
